package auth_system_menu

import (
	"encoding/json"
	"goskeleton/app/global/variable"
	"goskeleton/app/http/validator/web/auth/system_menu/data_type"
	"goskeleton/app/model/auth"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/qifengzhang007/sql_res_to_tree"
	"go.uber.org/zap"
)

type AuthSystemMenuService struct {
}

// 待分配系统菜单、mmodel、按钮树形化
func (a *AuthSystemMenuService) SystemMenuButtonToTree2(sqlRes []auth.AuthSystemMenuButton) []MenuListTree {
	var dest = make([]MenuListTree, 0)
	if err := sql_res_to_tree.CreateSqlResFormatFactory().ScanToTreeData(sqlRes, &dest); err == nil {
		return dest
	} else {
		variable.ZapLog.Error("sql结果数据树形化失败，错误明细：", zap.Error(err))
	}
	return nil
}

// 已分配给系统菜单、按钮树形化
func (a *AuthSystemMenuService) AssginedMenuButtonToTree(sqlRes []auth.AssignedSystemMenuButton) []AssignedSystemMenuButton {
	var dest = make([]AssignedSystemMenuButton, 0)
	if err := sql_res_to_tree.CreateSqlResFormatFactory().ScanToTreeData(sqlRes, &dest); err == nil {
		return dest
	} else {
		variable.ZapLog.Error("sql结果数据树形化失败，错误明细：", zap.Error(err))
	}
	return nil
}

// 处理按钮字符串
func (a *AuthSystemMenuService) ButtonStringToArray(jsonStr string) []map[string]interface{} {
	mSlice := make([]map[string]interface{}, 0)
	_ = json.Unmarshal([]byte(jsonStr), &mSlice)
	return mSlice
}

// 将按钮循环加入表中
func (a *AuthSystemMenuService) InsertButton(context *gin.Context, menuId int64) bool {
	if menuButtonList, isOk := context.MustGet(variable.SystemCreateKey).(data_type.MenuCreate); isOk {
		for index, item := range menuButtonList.ButtonArray {
			item.FrAuthSystemMenuId = menuId
			item.Status = 1
			item.CreatedAt = time.Now().Format(variable.DateFormat)
			item.UpdatedAt = item.CreatedAt
			menuButtonList.ButtonArray[index] = item
		}
		if len(menuButtonList.ButtonArray) > 0 && auth.CreateAuthSystemMenuButtonFactory("").InsertData(menuButtonList.ButtonArray) {
			return true
		} else if len(menuButtonList.ButtonArray) == 0 {
			return true
		}
	}
	return false
}

// 更新按钮数据
func (a *AuthSystemMenuService) UpdateButton(context *gin.Context, menuId int64) bool {
	if menuButtonList, isOk := context.MustGet(variable.SystemEditKey).(data_type.MenuEdit); isOk {
		//修改数据过程中可能存在单条数据被删除的情况，首先删除已标记的数据
		if len(menuButtonList.ButtonDelete) > 0 {
			auth.CreateAuthSystemMenuButtonFactory("").BatchDeleteData(menuButtonList.ButtonDelete)
		}
		for index, item := range menuButtonList.ButtonArray {
			item.FrAuthSystemMenuId = menuId
			item.Status = 1
			item.CreatedAt = time.Now().Format(variable.DateFormat)
			item.UpdatedAt = item.CreatedAt
			menuButtonList.ButtonArray[index] = item
		}
		if auth.CreateAuthSystemMenuButtonFactory("").UpdateData(menuButtonList) {
			go a.UpdateHook(menuId)
			return true
		}
	}
	return false
}

// 菜单挂接的待分配权限按钮数据被更新后，需要自动更新tb_auth_casbin_rule表数据
func (a *AuthSystemMenuService) UpdateHook(menuId int64) {
	auth.CreateAuthSystemMenuButtonFactory("").UpdateHook(menuId)
}

func (a *AuthSystemMenuService) GetAllData(fid int) (AllAuth []*auth.AllAuth) {
	return auth.CreateAuthOrganizationFactory("").GetAll(fid)
}

func (a *AuthSystemMenuService) GetAllDataByStatus() []auth.AuthOrganizationPostTree {
	// 直接调用GetAllAsTreeWithStatus方法获取树状结构
	treeData, err := auth.CreateAuthOrganizationFactory("").GetAllAsTreeWithStatus(1, 1)
	if err != nil {
		variable.ZapLog.Error("获取组织数据树状结构失败，错误明细：", zap.Error(err))
		return nil
	}
	return treeData
}

func (a *AuthSystemMenuService) GetFindById(id int) *auth.AuthOrganizationPostTree {
	// 创建AuthOrganizationPostModel实例
	var data auth.AuthOrganizationPostModel
	// 调用model层的方法获取数据
	err := auth.CreateAuthOrganizationFactory("").GetById(id, &data)
	if err != nil {
		variable.ZapLog.Error("根据ID获取组织数据失败，错误明细：", zap.Error(err))
		return nil
	}

	// 如果没有找到数据
	if data.Id == 0 {
		return nil
	}

	// 转换为AuthOrganizationPostTree格式
	treeData := &auth.AuthOrganizationPostTree{
		Id:       int(data.Id),
		Fid:      data.Fid, // 直接使用int类型的Fid
		Title:    data.Title,
		NodeType: data.NodeType,
		Status:   data.Status, // 直接使用int类型的Status
		PathInfo: data.PathInfo,
		Remark:   data.Remark,
		IsLeaf:   true, // 单个节点默认为叶子节点
		Children: []auth.AuthOrganizationPostTree{},
	}

	return treeData
}

// GetRolesOnly 仅获取角色/岗位数据（node_type=2）
func (a *AuthSystemMenuService) GetRolesOnly() []auth.AuthOrganizationPostTree {
	roles, err := auth.CreateAuthOrganizationFactory("").GetRolesOnly(1)
	if err != nil {
		variable.ZapLog.Error("获取角色数据失败，错误明细：", zap.Error(err))
		return nil
	}
	return roles
}

// GetPostsOnly 仅获取岗位数据（node_type=2，与GetRolesOnly相同）
func (a *AuthSystemMenuService) GetPostsOnly() []auth.AuthOrganizationPostTree {
	posts, err := auth.CreateAuthOrganizationFactory("").GetPostsOnly(1)
	if err != nil {
		variable.ZapLog.Error("获取岗位数据失败，错误明细：", zap.Error(err))
		return nil
	}
	return posts
}

// GetByNodeType 根据节点类型获取数据
func (a *AuthSystemMenuService) GetByNodeType(nodeType int) []auth.AuthOrganizationPostTree {
	result, err := auth.CreateAuthOrganizationFactory("").GetByNodeType(nodeType, 1)
	if err != nil {
		variable.ZapLog.Error("根据节点类型获取数据失败，错误明细：", zap.Error(err))
		return nil
	}
	return result
}

// GetDepartmentsOnly 仅获取部门数据（node_type=1）
func (a *AuthSystemMenuService) GetDepartmentsOnly() []auth.AuthOrganizationPostTree {
	departments, err := auth.CreateAuthOrganizationFactory("").GetDepartmentsOnly(1)
	if err != nil {
		variable.ZapLog.Error("获取部门数据失败，错误明细：", zap.Error(err))
		return nil
	}
	return departments
}

// GetDepartmentsAsTree 获取部门数据的树状结构（node_type=1, status=1）
func (a *AuthSystemMenuService) GetDepartmentsAsTree() []auth.AuthOrganizationPostTree {
	// 使用rootFid=0表示从顶级部门开始构建树状结构
	departmentTree, err := auth.CreateAuthOrganizationFactory("").GetDepartmentsAsTree(0)
	if err != nil {
		variable.ZapLog.Error("获取部门树状结构失败，错误明细：", zap.Error(err))
		return nil
	}
	return departmentTree
}

// GetAllRolesByFid 根据fid查询所有启用的角色/岗位数据，不分页
func (a *AuthSystemMenuService) GetAllRolesByFid(fid int) []auth.AuthOrganizationPostModel {
	data := auth.CreateAuthOrganizationFactory("").GetAllRolesByFid(fid)
	if len(data) == 0 {
		variable.ZapLog.Info("根据fid查询角色数据为空", zap.Int("fid", fid))
	}
	return data
}

func (a *AuthSystemMenuService) GetAllPostsByIds(ids []int) []auth.AuthOrganizationPostModel {
	data := auth.CreateAuthOrganizationFactory("").GetByIds(ids)
	if len(data) == 0 {
		variable.ZapLog.Info("根据ids查询岗位数据为空", zap.Ints("ids", ids))
	}
	return data
}

func (a *AuthSystemMenuService) GetAllPostsIdAndTitleByIds(ids []int) []auth.OrgPostIdAndTitle {
	data := auth.CreateAuthOrganizationFactory("").GetAllOrgPostIdAndTitleByIds(ids)
	if len(data) == 0 {
		variable.ZapLog.Info("根据ids查询岗位数据为空", zap.Ints("ids", ids))
	}
	// 将 []*auth.OrgPostIdAndTitle 转换为 []auth.OrgPostIdAndTitle
	var result []auth.OrgPostIdAndTitle
	for _, item := range data {
		if item != nil {
			result = append(result, *item)
		}
	}
	return result
}

func (a *AuthSystemMenuService) GetAllChildIdsById(id int, nodeType int) []int {
	childIds, err := auth.CreateAuthOrganizationFactory("").GetAllChildIdsById(id, nodeType)
	if err != nil {
		variable.ZapLog.Error("获取子节点ID失败，错误明细：", zap.Error(err))
		return nil
	}
	return childIds
}

func (a *AuthSystemMenuService) GetAllChildRoleIdNameById(id int, nodeType int) []auth.OrgPostIdAndTitle {
	childIds, err := auth.CreateAuthOrganizationFactory("").GetAllChildRoleIdNameById(id, nodeType)
	if err != nil {
		variable.ZapLog.Error("获取子节点ID失败，错误明细：", zap.Error(err))
		return nil
	}
	return childIds
}

func (a *AuthSystemMenuService) GetPositionLevelByLevel(level int) auth.PositionLevel {
	return auth.CreatePositionLevelFactory().GetPositionLevelByLevel(level)
}

func (a *AuthSystemMenuService) GetPositionLevelData() *auth.PositionIdLevel {
	return auth.CreatePositionLevelFactory()
}
